﻿namespace SimpleX.RBAC;

public class SpaService : DbRepository<SysMenu>, ISpaService
{
    /// <inheritdoc/>
    public async Task<SqlSugarPagedList<SysMenu>> Page(SpaPageInput input)
    {
        var query = Context.Queryable<SysMenu>()
                         .Where(it => it.Category == CateGoryConst.Menu_SPA)//单页
                         .WhereIF(!string.IsNullOrEmpty(input.MenuType), it => it.MenuType == input.MenuType)//根据菜单类型查询
                         .WhereIF(!string.IsNullOrEmpty(input.SearchKey), it => it.Title.Contains(input.SearchKey) || it.Path.Contains(input.SearchKey))//根据关键字查询
                         .OrderByIF(!string.IsNullOrEmpty(input.SortField), $"{input.SortField} {input.SortOrder}")
                         .OrderBy(it => it.SortCode);//排序
        var pageInfo = await query.ToPagedListAsync(input.Current, input.Size);//分页
        return pageInfo;
    }

    /// <inheritdoc />
    public async Task Add(SpaAddInput input)
    {
        var result = CheckInput(input);//检查参数
        if (result != "OK")
        {
            Unify.SetError(result);
            return;
        }
        input.Code = "R_" + IDUtils.GetId(); //code取随机值
        var sysResource = input.Adapt<SysMenu>();//实体转换
        await InsertAsync(sysResource);
    }

    /// <inheritdoc />
    public async Task Edit(SpaEditInput input)
    {
        var result = CheckInput(input);//检查参数
        if (result != "OK")
        {
            Unify.SetError(result);
            return;
        }
        var sysResource = input.Adapt<SysMenu>();//实体转换
        await UpdateAsync(sysResource);
    }

    /// <inheritdoc />
    public async Task Delete(List<BaseIdInput> input)
    {
        //获取所有ID
        var ids = input.Select(it => it.Id).ToList();
        if (ids.Count > 0)
        {
            var menus = await GetListAsync(x => ids.Contains(x.Id));

            //查找内置模块
            var system = menus.Where(it => it.Code == "system").FirstOrDefault();
            if (system != null)
                throw new Exception($"不可删除系统内置模块:{system.Title}");

            var result = await itenant.UseTranAsync(async () =>
            {
                await DeleteByIdsAsync(ids.Cast<object>().ToArray());
                await Context.Deleteable<SysRelation>().Where(x => ids.Contains(x.ObjectId) || ids.Contains(x.TargetId)).ExecuteCommandAsync();
            });
            if (!result.IsSuccess)//如果成功了
            {
                throw result.ErrorException;
            }
        }
    }

    #region 方法

    /// <summary>
    /// 检查输入参数
    /// </summary>
    /// <param name="sysResource"></param>
    private string CheckInput(SysMenu sysResource)
    {
        //判断菜单类型
        if (sysResource.MenuType == CateGoryConst.Menu_MENU)//如果是菜单
        {
            if (string.IsNullOrEmpty(sysResource.Name))
            {
                return $"单页名称不能为空";
            }
            if (string.IsNullOrEmpty(sysResource.Component))
            {
                return $"组件地址不能为空";
            }
        }
        else if (sysResource.MenuType == CateGoryConst.IFRAME || sysResource.MenuType == CateGoryConst.LINK)//如果是内链或者外链
        {
            sysResource.Name = "R_" + IDUtils.GetId();
            sysResource.Component = null;
        }
        else
        {
            return $"单页类型错误:{sysResource.MenuType}";//都不是
        }
        //设置为单页
        sysResource.Category = CateGoryConst.Menu_SPA;
        return "OK";
    }

    #endregion 方法
}